<?php
/**
 * Read Google Weather API
 * @author     Deepak Pradhan
 * @copyright  (c) 2009 GemiSoft
 * @license    GPL
 * @updates:   http://gemisoft.com/site/weather.html
 */

/**
 * Resource: http://dennisjaamann.com/blog/?p=49
 * Weather API : http://www.google.com/ig/api?
   API Param   : weather=location
   location    = {zip code} or {(city+name,state)}
*/

class GoogleWeatherAPI extends CWidget
{
    public $WeatherAPI = "http://www.google.com/ig/api?";
	public $location   = 63371;  //Default Location   
    public $weather    = array();

    public function init() 
	{
		
        $api   = $this->WeatherAPI.'weather='.$this->location.'&hl=zh-cn';
        $content = file_get_contents($api);
        $content || die("No such city's data");
        $content = mb_convert_encoding($content, 'UTF-8', 'GBK');
        $xml   = simplexml_load_string($content);
        $this->weather = $this->xml2assoc($xml);
    }

    private function xml2assoc($xml) 
	{
        $i = 0;
        foreach ($xml as $e) {
            foreach ($e as $name => $data) {
                if (($name == 'forecast_information') || ($name == 'current_conditions')) {
                    foreach ($data as $col => $val) {
                        $weather[$name][$col] = (string)$val['data'];
                    }
                }
                else {
                    foreach ($data as $col => $val) {
                        $weather['forecast'][$i][$col] = (string)$val['data'];
                    }
                    $i++;
                }
            }
        }
        return $weather;
    }

    public function run() 
	{
        $this->render('google_weather', array('weather'=>$this->weather));
    }
}
?>